import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:camera/camera.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';

class CameraScreen extends StatefulWidget {
  const CameraScreen({super.key});

  @override
  State<CameraScreen> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen>
    with WidgetsBindingObserver {
  CameraController? _controller;
  List<CameraDescription> cameras = [];
  bool _isInitialized = false;
  bool _isCapturing = false;

  // 添加预览尺寸状态
  Size? _previewSize;
  double? _previewAspectRatio;

  // 添加缩放状态
  double _minAvailableZoom = 1.0;
  double _maxAvailableZoom = 1.0;
  double _currentZoom = 1.0;
  double _baseScale = 1.0; // 添加基准缩放值

  // 添加对焦点状态
  Offset? _focusPoint;
  bool _showFocusPoint = false;

  @override
  void initState() {
    super.initState();
    // 设置全屏
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.immersiveSticky,
      overlays: [],
    );
    WidgetsBinding.instance.addObserver(this);
    _initializeCamera();
  }

  @override
  void dispose() {
    // 恢复系统UI
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: SystemUiOverlay.values,
    );
    WidgetsBinding.instance.removeObserver(this);
    _controller?.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final CameraController? cameraController = _controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      return;
    }

    if (state == AppLifecycleState.inactive) {
      cameraController.dispose();
    } else if (state == AppLifecycleState.resumed) {
      _initializeCamera();
    }
  }

  Future<bool> _requestPermissions() async {
    try {
      // 检查相机权限
      if (!await Permission.camera.isGranted) {
        final cameraResult = await Permission.camera.request();
        if (!cameraResult.isGranted) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('需要相机权限才能使用此功能'),
                duration: Duration(seconds: 2),
              ),
            );
            Navigator.pop(context);
          }
          return false;
        }
      }

      // 检查存储权限（Android）
      if (Platform.isAndroid) {
        // 检查存储权限
        if (!await Permission.storage.isGranted) {
          await Permission.storage.request();
        }

        // 检查照片权限
        if (!await Permission.photos.isGranted) {
          await Permission.photos.request();
        }
      }

      return true;
    } catch (e) {
      debugPrint('请求权限错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('请求权限失败: $e'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
      return false;
    }
  }

  Future<void> _initializeCamera() async {
    try {
      final hasPermissions = await _requestPermissions();
      if (!hasPermissions) return;

      cameras = await availableCameras();
      if (cameras.isNotEmpty) {
        // 强制设置为竖屏
        await SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
        ]);

        _controller = CameraController(
          cameras[0],
          ResolutionPreset.veryHigh, // 使用更高的分辨率
          enableAudio: false,
          imageFormatGroup: ImageFormatGroup.jpeg,
        );

        await _controller!.initialize();

        // 设置相机方向
        await _controller!.lockCaptureOrientation(DeviceOrientation.portraitUp);

        // 获取缩放范围
        _maxAvailableZoom = await _controller!.getMaxZoomLevel();
        _minAvailableZoom = await _controller!.getMinZoomLevel();

        // 设置相机参数
        await _controller!.setFocusMode(FocusMode.auto);
        await _controller!.setExposureMode(ExposureMode.auto);
        await _controller!.setFlashMode(FlashMode.auto);

        if (mounted) {
          setState(() {
            _isInitialized = true;
            _previewSize = _controller!.value.previewSize;
            if (_previewSize != null) {
              // 确保正确的预览方向
              _previewAspectRatio = _previewSize!.height / _previewSize!.width;
            }
          });
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('未找到可用的相机')),
          );
          Navigator.pop(context);
        }
      }
    } catch (e) {
      debugPrint('相机初始化错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('相机初始化失败: $e')),
        );
        Navigator.pop(context);
      }
    }
  }

  Future<String?> _takePicture() async {
    if (!_isInitialized || _controller == null) return null;

    try {
      // 拍照
      final XFile image = await _controller!.takePicture();

      // 获取应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      final imageName = 'captured_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final imagePath = path.join(directory.path, imageName);

      // 复制图片到应用目录
      await File(image.path).copy(imagePath);

      // 使用 MediaStore API 保存图片到相册
      if (Platform.isAndroid) {
        final result = await _saveImageToGalleryAndroid(imagePath);
        if (result) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('照片已保存到相册'),
                duration: Duration(seconds: 2),
              ),
            );
          }
          return imagePath;
        }
      } else {
        // 对于iOS，使用照片库权限
        if (await Permission.photos.request().isGranted) {
          // 使用原生方法通道保存到相册
          // TODO: 实现iOS的保存逻辑
          return imagePath;
        }
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('保存照片失败'),
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      debugPrint('拍照错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('拍照失败: $e'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    }
    return null;
  }

  Future<bool> _saveImageToGalleryAndroid(String imagePath) async {
    try {
      final file = File(imagePath);
      if (!await file.exists()) {
        return false;
      }

      // 创建 MediaStore 条目
      final result = await const MethodChannel(
              'com.example.foreign_exchange_translator/media_store')
          .invokeMethod<bool>('saveImage', {
        'path': imagePath,
        'name': path.basename(imagePath),
        'mimeType': 'image/jpeg',
      });

      return result ?? false;
    } catch (e) {
      debugPrint('保存图片到相册错误: $e');
      return false;
    }
  }

  // 添加对焦方法
  Future<void> _onTapToFocus(TapUpDetails details) async {
    if (_controller == null) return;

    final size = MediaQuery.of(context).size;
    final Offset tapPosition = details.localPosition;
    final double x = tapPosition.dx / size.width;
    final double y = tapPosition.dy / size.height;

    try {
      await _controller!.setFocusPoint(Offset(x, y));
      await _controller!.setExposurePoint(Offset(x, y));

      setState(() {
        _focusPoint = tapPosition;
        _showFocusPoint = true;
      });

      // 3秒后隐藏对焦点
      Future.delayed(const Duration(seconds: 3), () {
        if (mounted) {
          setState(() {
            _showFocusPoint = false;
          });
        }
      });
    } catch (e) {
      debugPrint('设置对焦点失败: $e');
    }
  }

  // 修改缩放方法
  Future<void> _onScaleStart(ScaleStartDetails details) async {
    _baseScale = _currentZoom;
  }

  Future<void> _onScaleUpdate(ScaleUpdateDetails details) async {
    if (_controller == null) return;

    // 降低缩放速度，增加平滑度
    final double scale = (_baseScale * (1 + (details.scale - 1) * 0.5))
        .clamp(_minAvailableZoom, _maxAvailableZoom);

    if ((scale - _currentZoom).abs() > 0.05) {
      // 添加阈值，避免频繁更新
      setState(() {
        _currentZoom = scale;
      });
      await _controller!.setZoomLevel(scale);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isInitialized || _controller == null || _previewSize == null) {
      return const Scaffold(
        backgroundColor: Colors.black,
        body: Center(child: CircularProgressIndicator(color: Colors.white)),
      );
    }

    // 获取屏幕尺寸
    final size = MediaQuery.of(context).size;

    // 计算预览比例
    final screenAspectRatio = size.height / size.width;
    final previewAspectRatio = _previewSize!.width / _previewSize!.height;

    // 计算缩放比例
    double scale = screenAspectRatio / previewAspectRatio;

    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        fit: StackFit.expand,
        children: [
          // 相机预览
          GestureDetector(
            onTapUp: _onTapToFocus,
            onScaleStart: _onScaleStart, // 添加 onScaleStart
            onScaleUpdate: _onScaleUpdate,
            child: Transform.scale(
              scale: scale,
              child: Center(
                child: CameraPreview(_controller!),
              ),
            ),
          ),

          // 添加缩放指示器
          Positioned(
            top: MediaQuery.of(context).padding.top + 60,
            right: 16,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                '${_currentZoom.toStringAsFixed(1)}x',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                ),
              ),
            ),
          ),

          // 对焦点指示器
          if (_showFocusPoint && _focusPoint != null)
            Positioned(
              left: _focusPoint!.dx - 20,
              top: _focusPoint!.dy - 20,
              child: Container(
                height: 40,
                width: 40,
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.white,
                    width: 1.5,
                  ),
                  shape: BoxShape.circle,
                ),
                child: const Center(
                  child: SizedBox(
                    height: 30,
                    width: 30,
                    child: CircularProgressIndicator(
                      color: Colors.white,
                      strokeWidth: 1,
                    ),
                  ),
                ),
              ),
            ),

          // 顶部操作栏
          Positioned(
            top: MediaQuery.of(context).padding.top,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black.withOpacity(0.7),
                    Colors.transparent,
                  ],
                ),
              ),
            ),
          ),

          // 底部操作区
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 20,
              ),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.bottomCenter,
                  end: Alignment.topCenter,
                  colors: [
                    Colors.black.withOpacity(0.7),
                    Colors.transparent,
                  ],
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  // 退出按钮
                  Material(
                    color: Colors.transparent,
                    child: InkWell(
                      onTap: () => Navigator.pop(context),
                      borderRadius: BorderRadius.circular(50),
                      child: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: Colors.black26,
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.close,
                          color: Colors.white,
                          size: 28,
                        ),
                      ),
                    ),
                  ),
                  // 拍照按钮
                  GestureDetector(
                    onTapDown: (_) => setState(() => _isCapturing = true),
                    onTapUp: (_) async {
                      setState(() => _isCapturing = false);
                      final imagePath = await _takePicture();
                      if (imagePath != null && mounted) {
                        HapticFeedback.mediumImpact();
                        Navigator.pop(context, imagePath);
                      }
                    },
                    onTapCancel: () => setState(() => _isCapturing = false),
                    child: AnimatedContainer(
                      duration: const Duration(milliseconds: 100),
                      width: _isCapturing ? 72 : 80,
                      height: _isCapturing ? 72 : 80,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white.withOpacity(0.9),
                        border: Border.all(
                          color: Colors.white,
                          width: 3,
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.3),
                            spreadRadius: 2,
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Center(
                        child: Container(
                          width: _isCapturing ? 60 : 68,
                          height: _isCapturing ? 60 : 68,
                          decoration: const BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  // 占位，保持对称
                  const SizedBox(width: 52),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
